﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Solidi
{
	public class DependencyResolver : IDependencyResolver
	{
		public object Resolve(IDependencyContext context, IDependencyKey key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}

			if (IsValueType(key))
			{
				throw new DependencyContainerException(String.Format("Cannot resolve value type {0}.", key));
			}

			IDependency[] dependencies = context.Registry.Find(key);

			if (dependencies.Length > 0)
			{
				return context.Lifetime.Resolve(context, dependencies[dependencies.Length - 1]);
			}

			return null;
		}

		public bool Release(IDependencyContainer container, object instance)
		{
			return container.Lifetime.Release(instance);
		}

		private bool IsValueType(IDependencyKey key)
		{
			return key.Type.IsValueType;
		}
	}
}
